#!/bin/bash
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

# Use this script to run the makefile within a docker container

AWS_CREDS_DIR="$HOME/.aws"
DOCKER_PROJECT_DIR="/opt/mozdef"
IMG_NAME="mozdef_builder"
HUB="mozdef"
CONTAINER_NAME="$IMG_NAME-container"

function usage() {
  echo "Build make targets in a container (${IMG_NAME})"
  echo "$0 make <make target>"
  exit 127
}

function check_img() {
  docker image ls ${IMG_NAME} 2>&1 > /dev/null && return 0
  echo "Cannot find docker image ${IMG_NAME}."
  echo "Please run \`make dkrbuild\` to build it, or \`docker pull ${HUB}/${IMG_NAME}\`".
  return 1
}

[[ $# -eq 0 ]] && usage

check_img || exit 127

if [ -n "$AWS_CONFIG_FILE" ]; then
  config_file_mount="-v ${AWS_CONFIG_FILE}:${AWS_CONFIG_FILE}"
fi

if [ -n "$AWS_SHARED_CREDENTIALS_FILE" ]; then
  config_file_mount="${config_file_mount} -v ${AWS_SHARED_CREDENTIALS_FILE}:${AWS_SHARED_CREDENTIALS_FILE}"
fi

dmake_env_file="`mktemp`"
trap "{ rm -f \"$dmake_env_file\"; }" EXIT
env | egrep "^AWS|OIDC_CLIENT_SECRET" > "$dmake_env_file"

exec docker run --rm --name ${CONTAINER_NAME} \
  -u $(id -u) \
  -v ${AWS_CREDS_DIR}:/root/.aws \
  ${config_file_mount} \
  -v $(pwd):${DOCKER_PROJECT_DIR} \
  --env-file "$dmake_env_file" \
  ${HUB}/${IMG_NAME}:latest make $@
